How to query a namespace programmatically

I am working on a Liberator project in Clojure. I have defined a number of routes that return JSON data computed by logic in a different namespace. I would like to be able to change the namespace that implements the logic programmatically, so I can do something like this:

JAVA_OPTS='-DgameLogicNamespace=foo.logic.mock' lein ring server-headless 8080

      

I am currently doing it like this:

(ns foo.routes
  (:require [compojure.core :refer :all]
            [liberator.core :as lib :refer [defresource request-method-in]]
            [liberator.representation :refer [ring-response]]))

(require
 (vec
  (cons (symbol (System/getProperty "gameLogicNamespace" "foo.logic.real"))
        '[:as logic])))

      

It works, but feels a little awkward. Is there an idiomatic way to accomplish what I want?

One of my main motivations is actually for unit test routes with mock data, so if there is a good solution for providing mock logic only in tests (not as a property of the JVM system) suggestions are welcome.

+2


source to share


1 answer


One of my main motivations is actually for unit test routes with mock data, so if there is a good solution for providing mock logic only in tests (not as a property of the JVM system) suggestions are welcome.

If you haven't already, take a look at ring-mock for some useful mock-request utilities to test Ring handlers.



If you are interested in providing mock versions of functions that provide logic for your application during unit tests, consider using with-redefs

; it is pretty much custom made for this purpose.

(ns my-app.handlers-test
  (:require [clojure.test]
            [my-app.handlers :as h]
            [my-app.logic :as l]
            [ring.mock.request :as r]))

(deftest test-simple-handler
  (with-redefs [l/my-complicated-logic #(update-in % [:a] inc)]
    (is (= {:a 2}
           (h/my-handler (r/request :post "/foo" {:a 1}))))))

      

+1


source







All Articles