Lifecycle Hooks
Lifecycle hooks allow you to execute custom logic at specific stages of the testing process. This is essential for managing provider state, such as setting up test data or cleaning up after an operation.
🔄 The Verification Lifecycle
The Drift engine emits events throughout the execution of a test suite. You can "hook" into these events using the event_handlers table in your Lua script.
| Event Name | Best Use Case |
|---|---|
testcase:started | Global setup (e.g., seeding a database). |
testcase:finished | Global cleanup after all operations complete. |
operation:started | Per-test setup (e.g., ensuring a specific record exists). |
operation:prepared | Modify operation parameters before invocation. |
operation:finished | Post-test cleanup (e.g., deleting created resources). |
operation:failed | Handle verification failures or log debugging info. |
http:request | Modifying headers or bodies immediately before dispatch. |
For a comprehensive list of all available events, see the Lua API Reference.
🛠️ Common Patterns
Data Cleanup (Teardown)
Use the operation:finished hook to reset your environment. This ensures that subsequent tests start with a clean slate.
-- product.lua
["operation:finished"] = function(event, data)
-- Perform a teardown request to a dev-only endpoint
local res = http({
url = "http://localhost:8080/teardown",
method = "POST",
body = ""
})
end
Dynamic Request Modification
If you need to inject a dynamic header (like a custom signature or an evolving token) into every request, use the http:request event.
["http:request"] = function(event, data)
-- data contains headers, method, and body
data.headers["x-request-timestamp"] = os.date("!%Y-%m-%dT%H:%M:%SZ")
-- Return the modified data to the engine
return data
end
Debugging with Lifecycle Data
When a hook isn't behaving as expected, use dbg() to inspect the metadata passed to the handler.
["operation:started"] = function(event, data)
-- data[2] typically contains the Operation ID
print("DEBUG: Starting " .. data[2])
print(dbg(data))
end