Skip to content

recordings

Johan Haleby edited this page Mar 24, 2017 · 15 revisions

Stub HTTP records all requests matching a specific response specification in an atom. You can get this atom from the server instance using :routes. For example:

(ns stub-http.example
  (:require [stub-http.core :refer :all]
            [clj-http.lite.client :as client]))

(with-open [server (start! { "/something" {:status 200 :content-type "text/plain" :body "body"}})]
    (client/get ,,,)
    (:routes server))

routes has the following schema:

[{:request-spec-fn  <function that takes a request (map) that returns true/false whether this spec matches the request>
 :request-spec     <the request specification map>
 :response-spec-fn <function that takes a request (map) and return the response-spec>
 :response-spec    <the response specification map>
 :recordings       <vector of recordings>}} ,,,]

So to get all recordings do something like this:

(mapcat :recordings (->> server :routes deref))

Each "recording" is a map with two keys, :request and :response that matches a specific route:

{:request <request>
 :response <response> }

The request has the following schema:

{:method       <keyword of http method, for example :get :post etc>
:headers      <map> 
:content-type <the content-type header>
:path         <the uri path>
:request-line <the request line (currently HTTP/1.1 is always added)
:body         <the request body>
:query-params <map>}

and the response is defined like this:

{:status <the status code as Int>
 :headers <map of name-value pairs>
 :content-type <shortcut for setting the "content-type" header>
 :body <The body as string>}

Convenience Functions

The server record contains two convenience functions that you can use to get the recorded requests and/or responses called recorded-requests and recorded-responses. Usage example:

(ns stub-http.example
  (:require [stub-http.core :refer :all]
            [clojure.test :refer :all]
            [clj-http.lite.client :as client]))

(with-open [server (start! { "/something" {:status 200 :content-type "text/plain" :body "body"}})]
    (client/get ...)
    (let [responses (recorded-responses server)]
         ; Now do something with the responses, for example count them      
         (is (= 1 (count responses)))))
Clone this wiki locally