Dredd supports hooks, which are blocks of arbitrary code that run before or after each test step. The concept is similar to XUnit’s
tearDown functions, Cucumber hooks, or Git hooks. Hooks are usually used for:
- Loading database fixtures,
- cleaning up after test step(s),
- handling auth and sessions,
- passing data between transactions (saving state from responses),
- modifying a request generated from the API description,
- changing generated expectations,
- setting custom expectations,
- debugging by logging stuff.
Let’s have a description of a blog API, which allows to list all articles, and to publish a new one.
Now let’s say the real instance of the API has the POST request protected so it is not possible for everyone to publish new articles. We do not want to hardcode secret tokens in our API description, but we want to get Dredd to pass the auth. This is where the hooks can help.
Hooks are functions, which are registered to be ran for a specific test step (HTTP transaction) and at a specific point in Dredd’s execution life cycle. Hook functions take one or more transaction objects, which they can modify. Let’s use hooks to add an Authorization header to Dredd’s request.
(Especially if your language of choice is Java, there’s an eternal fame and glory waiting for you - see #875)
Transaction names are path-like strings, which allow hook functions to address specific HTTP transactions. They intuitively follow the structure of your API description document.
You can get a list of all transaction names available in your API description document by calling Dredd with the
Types of hooks¶
Hooks get executed at specific points in Dredd’s execution life cycle. Available types of hooks are:
beforeAllcalled at the beginning of the whole test run
beforeEachcalled before each HTTP transaction
beforecalled before a specific HTTP transaction
beforeEachValidationcalled before each HTTP transaction is validated
beforeValidationcalled before a specific HTTP transaction is validated
aftercalled after a specific HTTP transaction regardless its result
afterEachcalled after each HTTP transaction
afterAllcalled after whole test run
Hooks inside Docker¶
However, hooks were not originally designed with this scenario in mind. Dredd gets a name of (or path to) the hook handler in
--language and then starts it as a child process. To work around this, fool Dredd with a dummy script and set
--hooks-worker-handler-host together with
--hooks-worker-handler-port to point Dredd’s TCP communication to the other container.
The issue described above is tracked in #755.