(ns puppetlabs.kitchensink.testutils
  (:require [fs.core :as fs]))

(defn call-counter
  "Returns a method that just tracks how many times it's called, and
  with what arguments. That information is stored in metadata for the
  method."
  []
  (let [ncalls    (ref 0)
        arguments (ref [])]
    (with-meta
      (fn [& args]
        (dosync
          (alter ncalls inc)
          (alter arguments conj args)))
      {:ncalls ncalls
       :args   arguments})))

(defn times-called
  "Returns the number of times a `call-counter` function has been
  invoked."
  [f]
  (deref (:ncalls (meta f))))

(defn delete-on-exit
  "Will delete `f` on shutdown of the JVM"
  [f]
  (do
    (.addShutdownHook (java.lang.Runtime/getRuntime) (Thread. #(fs/delete-dir f)))
    f))

(def ^{:doc "Creates a temporary file that will be deleted on JVM shutdown."}
  temp-file
  (comp delete-on-exit fs/temp-file))

(def ^{:doc "Creates a temporary directory that will be deleted on JVM shutdown."}
  temp-dir
  (comp delete-on-exit fs/temp-dir))

(ns puppetlabs.kitchensink.testutils
  (:require [fs.core :as fs]
            [puppetlabs.kitchensink.core :as ks]))

(defn call-counter
  "Returns a method that just tracks how many times it's called, and
  with what arguments. That information is stored in metadata for the
  method."
  []
  (let [ncalls    (ref 0)
        arguments (ref [])]
    (with-meta
      (fn [& args]
        (dosync
          (alter ncalls inc)
          (alter arguments conj args)))
      {:ncalls ncalls
       :args   arguments})))

(defn times-called
  "Returns the number of times a `call-counter` function has been
  invoked."
  [f]
  (deref (:ncalls (meta f))))

(defn delete-on-exit
  "Will delete `f` on shutdown of the JVM"
  [f]
  (do
    (.addShutdownHook (java.lang.Runtime/getRuntime) (Thread. #(fs/delete-dir f)))
    f))

(def ^{:doc "Creates a temporary file that will be deleted on JVM shutdown."}
  temp-file
  (comp delete-on-exit fs/temp-file))

(def ^{:doc "Creates a temporary directory that will be deleted on JVM shutdown."}
  temp-dir
  (comp delete-on-exit fs/temp-dir))

(defmacro with-no-jvm-shutdown-hooks
  [& body]
  `(with-redefs [ks/add-shutdown-hook! (fn [_#] nil)]
    ~@body))

Add macro for running a block of code w/o jvm shutdown hooks
Add macro for running a block of code w/o jvm shutdown hooks

camlow325/clj-kitchensink,mullr/clj-kitchensink