2

Unit-testing with Midje is a great experience, but now I need to test some code which interacts with the filessytem. Specifically, the code builds a data structure representation from a local directory layout.

Something that comes to mind is creating directories and files in /tmp, which then have to be cleaned up after the tests. I probably could make it work but it would be much better if there were a Right Way to do it.

What is the preferred way to test filesystem code, in Clojure or more generally?

jforberg
  • 6,537
  • 3
  • 29
  • 47

1 Answers1

1

I'm not sure whether there's specifically something that can help you with filesystem stuff already, but setup and teardown can be performed using background or against-background (if you need lexical scoping).

The general idea is similar to setup/teardown in other languages, you'd do something like this:

(require '[clojure.java.io :as io])

(background (before :facts (io/make-parents "parent/child/file")
            :after :facts (map io/delete-file (reverse (file-seq (io/file "parent")))

(facts "About something or other
  ...)

Before your facts, this will create the parent and child directories (not the file - you can add in a spit or something if you need the file too). Then after your facts it:

  • recursively gets a list of the contents of the parent directory (using file-seq)
  • reverses it (because we can only delete empty things, so must start at the bottom of the directory tree)
  • applies the delete-file function to each directory in the tree

The code there to create and delete files may not be the best (I'm new to this!), but the approach for setting up and tearing down stuff in Midje tests is sound.

Things to note:

  • Be careful with symlinks in your tree when using this approach, you could get stuck in a loop.
  • The :after syntax instead of using an (after) macro is there to ensure the teardown occurs even if the test throws an exception.
  • You can do the setup/teardown after a subset of facts in a single namespace by wrapping them with (against-background) and doing the same thing instead.

References:

https://github.com/marick/Midje/wiki/Setup,-Teardown,-and-State https://github.com/marick/Midje/wiki/Background-prerequisites

Conan
  • 2,288
  • 1
  • 28
  • 42