Object Commando languages, development and design


Mocking Clojure Protocols with Atticus

Atticus is a mocking library written by Hugo Duncan. For more information on Atticus, you can see Hugo's blog post from May here. I have added the ability to mock protocols to Atticus and would like some feedback as to the best approach for binding the mocked protocol instance. There's a survey below, but first a little background on the implementation.

Mocking Protocols

What makes the protocol instances a bit tough to mock is that they're not just straight Clojure functions. They dip a bit into Java and a bit into Clojure. With that in mind, using Atticus without modification, wouldn't allow the mocking of those protocols. Below is an example of some code that uses this new functionality:

(defprotocol Squared
  (square [impl x]))

(deftest mock-protocol-test
   [(instance Squared
	      (square [impl y] (once (* y y))))]
   (is (= 9 (square instance 3)))))

Originally I had a marker function name mock-protocol-instance which didn't serve much purpose and was a bit awkward. Talking with Hugo, I switched it to the above syntax. The first item in that list is instance and is the symbol that the mocked protocol instance is bound to. The next item is the protocol followed by functions. The (once...) wrapped around the body of the function is existing functionality in Atticus that expands into the code to ensure the function was called exactly once. An example of mocking a regular function in Atticus is below:

(deftest test-cube
   [(cube [y] (once (* y y y)))]
   (is (= 8 (cube 2)))))

The difference in this code and the first is that the binding syntax is familiar because it is similar to letfn. Below is an example of letfn:

(letfn [(add5 [x] (+ x 5))
	(subtract5 [x] (- x 5))]
  (= 7 (add5 (subtract5 7))))

In the style above, the first argument is the function name and so anything that refers to add5 in the body of the letfn gets the function bound above in the letfn. This letfn type of binding makes sense for Atticus when mocking functions. They both have similar goals, binding a function temporarily. Where this is a little more tricky is in mocking the protocol. In the first example above, the first element in the list is special. It's the symbol bound to the protocol instance. This is really more appropriate for a let style of binding. Where one element is the symbol and the other is an expression. Unfortunately, switching to a let style binding for the expects macro will make the syntax a little more cumbersome for mocking functions because you would have to add "fn". This would probably look something like this:

(deftest mock-protocol-test-alt
    [instance (Squared
	       (square [impl y] (once (* y y))))
     cube (fn [y] (once (* y y y)))]
        (is (= 9 (square instance 3)))
	(is (= 8 (cube y 2)))))

The above is just spit balling, but the key point is that expects would use a let binding style. The first is a let style binding of the protocol instance and the second is binding a function.

Put it to a vote!

The question is, which one is better? Is sticking with the letfn binding and the brevity that it allows worth it even though the protocol mocking is a bit different? The letfn style is the first and second code examples above. Or is it confusing enough to warrant a little extra code around mocking functions (the example immediately above). Is there another approach that would be better? Below is just a quick survey on which one is preferable. Thanks for giving your input!


Clojure Futures

Futures in Clojure are basically a way that you can execute some bit of code on a background thread. I was using it as a way to allow timeouts for long running code. In this entry I'll give a run down on how to use futures.

Future Basics

It is pretty easy to start using futures in Clojure. Most of the function calls start with (future...). First I'll start by creating a future that calls a long running sleep function:

(def f
    (println "Starting to sleep...")
    (Thread/sleep 600000)
    (println "Done sleeping.")))

There are two ways via Clojure to create a future, the first is with the macro future (used above), the other is the future-call function. The future macro is just syntax sugar around future-call. Whatever you pass in to future with be wrapped in a no-arg function and passed to future-call. The future-call function just invokes the passed in function on background type of thread. The above code, even though it sleeps for an hour will return immediately. The object returned is a future (intentionally not getting into details about what is returned right now). This returned future allows you to peek inside the execution of the code passed in and get information like is it done, or has it been canceled:

(future-done? f)
=> false

(future-cancelled? f)
=> false

You can then decide to cancel the future:

(future-cancel f)

(future-cancel f)

The above will return false when it was not able to cancel the future. As an example, if we try to cancel the future again, it will return false, because it has already been canceled. Another set of useful functions is getting the value returned by the executing future. Let's say we're still computing Fibonacci numbers in the slow, recursive way:

(defn fib [x]
  (cond (zero? x) 0
            (= 1 x) 1
	    (+ (fib (- x 1)) (fib (- x 2)))))

Computing (fib 40) on my laptop takes about 10 seconds. Below is code to execute the code in a future and then use deref to pull the value out:

(def f (future-call #(fib 40)))
=> #'user/f

(time @f)
=> "Elapsed time: 8075.452326 msecs"

(time @f)
=> "Elapsed time: 0.082342 msecs"

The first deref (@) call will block until the future has completed running and then return the value. So timing the deref, it took about 8 seconds until returning the value. But if it has already computed the value, it will just return that computed value. So the second deref returns very quickly.


One thing that is hidden from users of futures in Clojure is what is actually returned when calling (future...). I say that it's hidden because when you use future-cancel, future-done? etc, it doesn't matter what kind of object is returned from the future function call. It's some object that you are able to pass to these other functions and it just works. Where you actually do need to know more about the implementation of this is when you want to have your future timeout. The object returned by future-call is an implementation of java.util.concurrent.Future. With this information, you can use the Java APIs for the Future. Below is some code that creates a future that will timeout before it finishes:

(def f (future-call #(fib 50)))
(.get f 10 (java.util.concurrent.TimeUnit/SECONDS))

The last line does the same thing that we did before when we deref'd the future, but this time there is a timeout on how long we will wait for that deref to happen. If the timeout is reached (in this case 10 seconds), it will throw a java.util.concurrent.TimeoutException. Armed with the knowledge that the future is actually a java.util.concurrent.Future, the deref is just a more Clojure way of calling the get method on the future:

(def f (future-call #(fib 40)))
=> #'user/f

(time (.get f))
=> "Elapsed time: 10713.176672 msecs"

(time (.get f))
=> "Elapsed time: 0.075569 msecs"

Hey, where did my console output go?

I use Emacs and Slime for my development environment. One thing that I noticed was that code running in a future does not write to the console like code running from the Slime REPL. This is because code running in the Slime REPL gets the bound variables from the REPL thread, whereas the future code runs in a different thread that does not have those variables bound. bound-fn makes it easy to fix this problem:

(def f (future-call #(println "Hello World")))

(def f (future-call (bound-fn [] (println "Hello World"))))
=>Hello World
Filed under: Clojure 3 Comments