Doug's Blog

Mocking Drupal 7 Core Functions in Tests

Recently I needed to test a function that involved the drupal_valid_token function. There are no hooks for this function and it will generate new tokens with each user session. I needed to verify an external API’s cryptographic signature and a part of that signature involved a nonce for which I used the drupal_get_token function. I didn’t want to hit the API over and over again to run tests, but without a hook in the drupal_valid_token function there was no easy way for me to use static data as a test against the signature verification function. In Drupal 8 much of this is irrelevant because tests can exist inside of their own namespaces.

I solved this by wrapping my class in it’s own namespace “Org\Module”, then I placed the test suite inside the same namespace. Then I created another class which extends the original test back inside the global namespace so that Drupal will load the class when looking for tests. This let’s me have my own drupal_valid_token function that operates differently only for this test.