2

I'm trying to use ERT to test the ycmd package, and part of what I need to do is pass bodies of code to the ycmd server and ask for completion candidates. I'd like to be able to keep these bodies of code in separate files, partly for organization and partly because that makes it simpler to determine the position in the code for which I would like to do completion.

However, I can't figure out the right way to address these files when the test is running. The crux of what I want to do is read the contents of a file which is in a location relative to the elisp file which defines the test. How can I do this?

(I've tried load-file-name, and it appears that this might work for batch mode testing. However, it doesn't work for interactive testing inside emacs, so at best it's an incomplete solution.)

abingham
  • 927
  • 6
  • 18

1 Answers1

2

When a file is loaded, load-file-name is set. When a form is evaluated interactively from a file, buffer-file-name is set. So you can use (or load-file-name buffer-file-name) as the value of a global variable. You can then use file-name-directory and such to get parent directories.

If you use the f.el file name library, you can use something like (f-parent (f-dirname (f-this-file)))

Jorgen Schäfer
  • 3,899
  • 2
  • 17
  • 19
  • Ah-ha! I had already tried `(or load-file-name buffer-file-name)` with no success, but it turns out that the problem was with the context in which I was using it. If you use `buffer-file-name` inside the test itself (i.e. the body of the `ert-deftest`) it returns nil. But I was able to read the file contents into a global variable at file eval time, and that works perfectly. Thanks for convincing me to try again! – abingham Nov 24 '14 at 06:09
  • More precisely, `load-file-name` is set **while** (and only while) a file is being loaded. You can access it in top-level forms, but **not** the body of a function. –  Nov 24 '14 at 09:51