I'm trying to write some tests with Clojure. One of these tests involves opening an html file in the same directory as the running test file, to use the contents as test input (a widely-used idiom in Python). I thought the *file*
var would do the job, but that's not really the case, since it's relative.
Let's say my project, which uses the default leiningen layout, is called demoproj
. My tests are then in ~/projects/demoproj/test
. This directory replicates the project namespace again, which I'm not a big fan of, but whatever. So the tests for core.clj
are in ~/projects/demoproj/test/demoproj/test/core.clj
. I also have a file called small_page.html
in the same directory. If I put the following into test/core.clj
:
(println (-> (java.io.File. *file*)
.getPath))
Here's what I get:
demoproj/test/readibility.clj
This is relative to the test
directory of the project base. I tried reading the sample html page using only this relative path, as follows:
(slurp (-> (java.io.File. *file*)
.getParent
(java.io.File. "small_page.html")
.getPath))
This causes an IO error because the file cannot be read at that location. My next idea was to get the current working directory and join it with the relative path. Here is how I fetched the working directory:
(println (-> (java.io.File. ".")
.getCanonicalPath))
Which returned an absolute path:
/Path-to-home/projects/demoproj
The bad thing is, these two don't join to the correct path to the file; there's a test
component missing in between. Joining these two paths thus leads to an incorrect directory path.
So, my question would be, is there a reliable way to get the absolute path of the code file currently executed? And if this is not possible, what would be an alternative to this idiom, i.e. how could I parse a file that is in a location relative to the test file?