We can use the marklogic-unit-test framework to test custom APIs hosted in MarkLogic. Doing so is more of an integration test than a unit test, allowing us to ensure that HTTP inputs are correctly mapped to function parameters and that the API call works all the way through.
So why don’t we just do this? A couple reasons.
First, HTTP calls are slower than library calls. Second, when an API-level test fails, there may be a lot of code that was run. Why did it fail can be a pretty involved question.
The nice thing about unit tests is that you can be very focused on a specific piece of functionality. The nice thing about integration tests is making sure those pieces work together. There’s room for both.
Suppose we do want to build some API-level tests. We can do that using MarkLogic’s
xdmp.httpPost, and other functions. That brings us to an important question — how do we authenticate those calls?
MarkLogic has a great feature for this: Secure Credentials. Secure Credentials are a way to let application code make use of a set of credentials without recording a password in the modules database. For testing, we want to create a user that has the required roles for the test, but we want to do so in a secure way.
For a test suite, we can decide on the name of a Secure Credential that we’ll use for that suite. In
suiteSetup.sjs, we can create a new user with a UUID in the name and use a UUID for the password. This user is granted the roles needed to call the API.
We then create a secure credential with the previously determined name for that username, targeting
%%mlHost%% and the test port that we’re using. Now we can run our tests. Our test code not only doesn’t have the password embedded, it doesn’t even know what it is — it was randomly selected while creating the user and credential and then forgotten.
After our tests, the
suiteTeardown can remove the credential. We can get the name of the user from the credential, so we can remove the user at the same time.
This approach allows us to build tests using HTTP calls in a secure way. As always, you should only grant this user the roles needed to call the API. This helps ensure that your security setup is valid as well as your code.