Current directory for dune test

I have tests which need to read files. Static files, so right now I have them all checked in under the test subdirectory of the project. But, now I don’t know what pathname should I use to open them in the test code? Clearly absolute won’t do, so relative but relative to what? This comes down to, what is the current directory when dune runs my test executable. Can I control what that directory is? Or is there a way to retrieve the dune root from my test code?

Sorry if this is a FAQ - I feel it probably is :-o


Ian

1 Like

Dune uses a special randomized directory to run tests there.
I will speculate that you are asking about cram tests. In this case you should add to your dune file something like (cram (deps ./input.txt)). Look for more details at https://dune.rtfd.io

It’s been a while since I’ve checked the dune docs about this, so I’m not 100% confident about this, but speaking from my experience with testing using dune - while the directory under which the tests are run might be randomly generated during the test, the relative structure of the directory will mirror that of your overall project - so, when referencing external files from within a test, write the relative path as if the current directory was the folder in which the test file is written (but make sure to list all static files you need as explicit dependencies, or otherwise dune will not ensure that they are present when the test is running).

Example:

$ tree .
.
|-- dune-project
|-- resources/
|        `-- data.txt
`-- test/
         |-- test.ml 
         `-- dune

Inside test/dune:

(test (name test)
    (deps ../resources/data.txt))

Inside test/test.ml:

let ic = open_in "../resources/data.txt"
...

That webpage is slowly rising to the top of my “recently used” pages in Firefox, but I cannot immediately see which section answers my question. Can you specify more precisely?

Btw, I’m trying to do this from OUnit, not cram tests. To describe a bit more, I’m writing a parser for a file format; test parsing (or even lexing) each test file results in a data structure, and my test compares the data structure to the known expected one.

If you have a better idea how to test this kind of program, I’m open …


Ian

Thanks, this seems to work!


Ian