3
votes

I'm developing an clojure API and I want to everytime I start my server, run the tests before it.

I've found the function (run-tests) and (run-all-tests) but clojure says that this function does not exist at that namespace. If I put (:use clojure.test) at my ns, the function works, but it runs tests from libs that I'm using and from clojure core.

Here is my handler, where I placed the main method, then I want that "lein run" runs my tests then start the server.

(ns clojure-api.handler
  (:use compojure.core)
  (:require [compojure.route :as route]
            [org.httpkit.server :refer [run-server]]))

(defroutes app-routes 
    ;routes...
)

(def app
  (-> app-routes
      ;Some middleware))

(defn -main  
  [& args]
  (println "Running bank tests")
  (run-all-tests)
  (println "Starting server")
  (run-server app {:port 3000}))
2
Typically you have some type of CI setup that runs the tests before deploying. This isn't a typical way to handle running tests. You could just write a bash script that runs the tests and if successful run the server. That may be more simple to implement? I'm making an assumption that you don't need to specifically run the tests in the manner mentioned in your question.Slae
Also note, that whatever way you chose to run the tests, you might have to put them now under your regular sources to actually have them ready to run. E.g. if you want to do that with your uberjar, then the test files are usually not part of the generated artifact.cfrick
I understand that this is not a typical structure, but I wanted to run the tests before the server because this application is a college project and this procedure would be used for the presentation.pitalig

2 Answers

1
votes

You can specify for what namespaces to run tests via (run-tests 'ns-one-test 'ns-two-test).

(defn -main  
  [& args]
  (println "Running bank tests")
  (run-tests 'ns-one-test 'ns-two-test)
  (println "Starting server")
  (run-server app {:port 3000}))

This would work and only run the tests in the specified namespaces.

As the comments state, tests are usually run in a setup before a deploy (by using for example Jenkins, GitLab or CircleCI). When a test fails the next step is not executed, a report is shown somewhere, and the code is not deployed.

1
votes

if your project is a leiningen project, you can define an alias in the project.clj that combine the test und run tasks like this:

:aliases {"test-and-run" ["do" "test" "run"]}

;; .lein.sh test-and-run