servant-quickcheck- QuickCheck entire APIs

Safe HaskellNone




Servant.QuickCheck provides utilities related to using QuickCheck over an API. Rather than specifying properties that individual handlers must satisfy, you can state properties that ought to hold true of the entire API.

While the API must be described with servant types, the server being tested itself need not be implemented with servant-server (or indeed, written in Haskell).

The documentation of the Useful predicates sections is meant to serve as a set of helpful pointers for learning more about best practices concerning REST APIs.


Property testing

serverSatisfies :: HasGenRequest a => Proxy a -> BaseUrl -> Args -> Predicates [Text] [Text] -> Expectation Source

Check that a server satisfies the set of properties specified.

Note that, rather than having separate tests for each property you'd like to test, you should generally prefer to combine all properties into a single test. This enables a more parsimonious generation of requests and responses with the same testing depth.

Example usage:

goodAPISpec = describe "my server" $ do

  it "follows best practices" $ do
    withServantServer api server $ \burl ->
      serverSatisfies api burl stdArgs (not500
                                    <%> onlyJsonObjects
                                    <%> notAllowedContainsAllowHeader
                                    <%> mempty)



Useful predicates

The predicates below are often useful. Some check RFC compliance; some are best practice, and some are useful to check that APIs follow in-house best-practices. Included in the documentation for each is a list of references to any relevant RFCs and other links, as well as what type of predicate it is (RFC Compliance, Best Practice, Optional).

RFCs distinguish between the force of requirements (e.g. MUST vs. SHOULD). RFC Compliance includes any absolute requirements present in RFCs. The Best Practices includes, in addition to RFC recommendations, recommendations found elsewhere or generally accepted.

not500 :: ResponsePredicate Text Bool Source

Best Practice

500 Internal Server Error should be avoided - it may represent some issue with the application code, and it moreover gives the client little indication of how to proceed or what went wrong.

This function checks that the response code is not 500.


onlyJsonObjects :: ResponsePredicate Text Bool Source

Best Practice

Returning anything other than an object when returning JSON is considered bad practice, as:

  1. it is hard to modify the returned value while maintaining backwards compatibility
  2. many older tools do not support top-level arrays
  3. whether top-level numbers, booleans, or strings are valid JSON depends on what RFC you're going by
  4. there are security issues with top-level arrays

This function checks that any application/json responses only return JSON objects (and not arrays, strings, numbers, or booleans) at the top level.



notAllowedContainsAllowHeader :: RequestPredicate Text Bool Source

RFC Compliance

When an HTTP request has a method that is not allowed, a 405 response should be returned. Additionally, it is good practice to return an Allow header with the list of allowed methods.

This function checks that every 405 Method Not Allowed response contains an Allow header with a list of standard HTTP methods.



unauthorizedContainsWWWAuthenticate :: ResponsePredicate Text Bool Source

RFC Compliance

Any 401 Unauthorized response must include a WWW-Authenticate header.

This function checks that, if a response has status code 401, it contains a WWW-Authenticate header.



getsHaveCacheControlHeader :: RequestPredicate Text Bool Source

Best Practice

Whether or not a representation should be cached, it is good practice to have a Cache-Control header for GET requests. If the representation should not be cached, used Cache-Control: no-cache.

This function checks that GET responses have Cache-Control header. It does NOT currently check that the header is valid.



headsHaveCacheControlHeader :: RequestPredicate Text Bool Source

Best Practice

Like getsHaveCacheControlHeader, but for HEAD requests.


createContainsValidLocation :: RequestPredicate Text Bool Source


When creating a new resource, it is good practice to provide a Location header with a link to the created resource.

This function checks that every 201 Created response contains a Location header, and that the link in it responds with a 2XX response code to GET requests.

This is considered optional because other means of linking to the resource (e.g. via the response body) are also acceptable; linking to the resource in some way is considered best practice.



Predicate utilities and types

(<%>) :: JoinPreds a => a -> Predicates [Text] [Text] -> Predicates [Text] [Text] infixr 6 Source

Adds a new predicate (either ResponsePredicate or RequestPredicate) to the existing predicates.

not500 <%> onlyJsonObjects <%> empty


data Predicates n r Source

A set of predicates. Construct one with mempty and <%>.

data RequestPredicate n r Source

A predicate that depends on both the request and the response.





reqPredName :: n
reqResps :: Request -> Manager -> IO (r, [Response ByteString])

Equality testing

serversEqual :: HasGenRequest a => Proxy a -> BaseUrl -> BaseUrl -> Args -> ResponseEquality ByteString -> Expectation Source

Check that the two servers running under the provided BaseUrls behave identically by randomly generating arguments (captures, query params, request bodies, headers, etc.) expected by the server. If, given the same request, the response is not the same (according to the definition of == for the return datatype), the Expectation fails, printing the counterexample.

The Int argument specifies maximum number of test cases to generate and run.

Evidently, if the behaviour of the server is expected to be non-deterministic, this function may produce spurious failures


Response equality

Often the normal equality of responses is not what we want. For example, if responses contain a Date header with the time of the response, responses will fail to be equal even though they morally are. This datatype represents other means of checking equality *** Useful ResponseEqualitys

bodyEquality :: Eq b => ResponseEquality b Source

ByteString Eq instance over the response body.


allEquality :: Eq b => ResponseEquality b Source

Use Eq instance for Response


Response equality type

Test setup helpers

Helpers to setup and teardown servant servers during tests.

withServantServer :: HasServer a `[]` => Proxy a -> IO (Server a) -> (BaseUrl -> IO r) -> IO r Source

Start a servant application on an open port, run the provided function, then stop the application.


withServantServerAndContext :: HasServer a ctx => Proxy a -> Context ctx -> IO (Server a) -> (BaseUrl -> IO r) -> IO r Source

Like withServantServer, but allows passing in a Context to the application.


defaultArgs :: Args Source

QuickCheck Args with 1000 rather than 100 test cases.



Types and constructors from other packages that are generally needed for using servant-quickcheck.

data BaseUrl :: *

Simple data type to represent the target of HTTP requests for servant's automatically-generated clients.




baseUrlScheme :: Scheme

URI scheme to use

baseUrlHost :: String

host (eg "")

baseUrlPort :: Int

port (eg 80)

baseUrlPath :: String

path (eg "ab/c")


Eq BaseUrl 
Ord BaseUrl 
Show BaseUrl 
Generic BaseUrl 
type Rep BaseUrl = D1 D1BaseUrl (C1 C1_0BaseUrl ((:*:) ((:*:) (S1 S1_0_0BaseUrl (Rec0 Scheme)) (S1 S1_0_1BaseUrl (Rec0 String))) ((:*:) (S1 S1_0_2BaseUrl (Rec0 Int)) (S1 S1_0_3BaseUrl (Rec0 String))))) 

data Scheme :: *

URI scheme to use







Eq Scheme 
Ord Scheme 
Show Scheme 
Generic Scheme 
type Rep Scheme = D1 D1Scheme ((:+:) (C1 C1_0Scheme U1) (C1 C1_1Scheme U1)) 

data Args :: *

Args specifies arguments to the QuickCheck driver




replay :: Maybe (QCGen, Int)

Should we replay a previous test? Note: saving a seed from one version of QuickCheck and replaying it in another is not supported. If you want to store a test case permanently you should save the test case itself.

maxSuccess :: Int

Maximum number of successful tests before succeeding

maxDiscardRatio :: Int

Maximum number of discarded tests per successful test before giving up

maxSize :: Int

Size to use for the biggest test cases

chatty :: Bool

Whether to print anything


data Proxy t :: k -> *

A concrete, poly-kinded proxy type




Monad (Proxy *) 
Functor (Proxy *) 
Applicative (Proxy *) 
Foldable (Proxy *) 
Traversable (Proxy *) 
Bounded (Proxy k s) 
Enum (Proxy k s) 
Eq (Proxy k s) 
Ord (Proxy k s) 
Read (Proxy k s) 
Show (Proxy k s) 
Ix (Proxy k s) 
Generic (Proxy * t) 
Monoid (Proxy k s) 
Semigroup (Proxy k s) 
type Rep (Proxy k t) = D1 D1Proxy (C1 C1_0Proxy U1)