Search code examples
erlang

Erlang: How to assertMatch IoDevice value?


I am trying to write a test for opening a file. File open returns a value of the form:

{ok, IoDevice} | {error, Reason}

IoDevice example value is: <0.941.0>

I have tried the following so far (some of them I didn't believe they would succeed anyway...):

?assertMatch([], theIoDevice).
?assertMatch("[]", theIoDevice).
?assertMatch(<>, theIoDevice). % Won't compile 

and several more tests, but I fail.

What is the way to match the IoDevice pattern?

Is there possibility to match to Regular Expression?


Solution

  • file:open/2 always returns a tuple with two elements:

    1. The atom ok and the pid of a process handling the file (a genserver).

    or:

    1. The atom error and a string. But because a string is a shortcut for creating a list, the tuple really contains the atom error and a list.

    But theIoDevice is an atom that will never match an empty list, [], or the two element list, "[]", which is a shortcut for creating the list [91,93].

    You can't know the pid of the process that is handling a file ahead of time, so you can't try to match a specific pid, but you could assert that you got {ok, _} back from file:open/2. If you wanted to get more granular, you could check the second element with is_pid/1:

    ?assert(is_pid(File)).
    

    You can manually create a pid like this:

    list_to_pid("<0.4.1>") -> pid()